<?php
namespace Home\Server;

use Home\Server\ParcelService;

class QueryParcelService extends ParcelService{

    /**
     * @desc 拒收包裹
     * @author quyang
     * @update 2017-1-19
     */
    public function RejectParcel($data){

        $where['f_station_id'] = $data['stationId'];
        $where['f_parcel_id'] = array('in',$data['packetId']);

        $Array = array(
            'f_comment'=>$data['content'],
            'f_parcel_status'=>4,
            'f_last_time'=>date('YmdHis'),
            'f_last_timestamp'=>time()
        );

        //更新最近两个月表
        $NowTableResult  = ( new \Think\Model() ) ->table( $this ->Month_TableName_Now ) ->where($where) ->save( $Array );

        $LastTableResult = ( new \Think\Model() ) ->table( $this ->LastTableName ) ->where($where) ->save( $Array );

        return $NowTableResult || $LastTableResult ? True : False;
    }

    /**
     * Function RejectParcel_TableName
     * @param $station_id
     * @param $parcelID
     * @param $content
     * @param $tableName
     * @return bool
     *
     * Author: 黄盖
     * Date: 2017-2-9 13:49
     * Info: 拒收新操作
     */
    public function RejectParcel_TableName( $station_id, $parcelID, $content, $tableName )
    {
        if( empty( $tableName ) )
        {
            return False;
        }


        //待更新数据
        $Updata = Array(
            'f_parcel_status'   => 4,
            'f_last_time'       => date('YmdHis', $this ->NowTime),
            'f_last_timestamp'  => $this ->NowTime,
            'f_comment'         => $content
        );

        //更新
        $TableResult  = ( new \Think\Model() ) ->table( $tableName ) ->where("`f_parcel_id` IN ( {$parcelID} ) AND `f_station_id` = '{$station_id}'") ->save( $Updata );

        return $TableResult ? True : False;
    }

    /**
     * @desc 重发短信获取包裹信息
     * @author quyang
     * @update 2017-1-19
     */
    public function getParcelDetails($parcelId){

        $where = "`f_parcel_id`={$parcelId}";

        $field = '
                 f_company_name as companyName,
                 f_mail_no as mailNo,
                 f_take_code as extractCode,
                 f_recipient_mobile as mobile,
                 f_station_id as stationId,
                 f_parcel_id as packageCode,
                 f_frame_code as fFrameCode,
                 f_num as fNum
                 ';

         $data = $this->getUnion_TableResource($field,$where)
             ->field( ' temp_parcel_info.*,
                        ua.f_address as address,
                        ua.f_store_time as openTime,
                        ua.f_user_phone as userPhone,
                        ua.f_buy_count as fBuyCount,
                        ua.f_template_id as fTemplateId'
             )
             ->join('tp_user ua on ua.f_user_id = temp_parcel_info.stationId','LEFT')-> find();

        return $data;

    }


    /**
     * Function updateParcel
     * @param $parcelId
     *
     * Author: quyang
     * Date: 2017-1-20 9:31
     * Info: 更新包裹状态   通用
     */
    public function updateParcel( $where , $Array , $tableName = null ){

        if ( empty( $tableName ) )
        {
            //更新最近两个月表
            $NowTableResult  = ( new \Think\Model() ) ->table( $this ->Month_TableName_Now ) ->where($where) ->save( $Array );

            $LastTableResult = ( new \Think\Model() ) ->table( $this ->LastTableName ) ->where($where) ->save( $Array );

            return $NowTableResult || $LastTableResult ? True : False;
        }

        return ( new \Think\Model() ) ->table( $tableName ) ->where($where) ->save( $Array );

    }

    /**
     * @desc 获取包裹详情（发送失败重发通知）
     * @author quyang
     * @update 2017-1-19
     */
    public function reSendParcelDetails($parcelId){

        $where = "`f_parcel_id`={$parcelId}";

        $field = '
                 *
                 ';

        $data = $this->getUnion_TableResource($field,$where)
            ->field( ' temp_parcel_info.*,
                        ua.f_address,
                        ua.f_store_time,
                        ua.f_user_mobile,
                        ua.f_station_name'
            )
            ->join('tp_user ua on ua.f_user_id = temp_parcel_info.f_station_id','LEFT')-> find();

        return $data;

    }


    /**
     * @desc 获取包裹详情（编辑收件人资料）
     * @author quyang
     * @update 2017-1-19
     */
    public function queryParcelDetails($parcelId, $appointDate = '' )
    {
        //201702  >  2017-02
        if( $appointDate != '' )
        {
            $appointDate = substr( $appointDate, 0, 4 ) . '-' . substr( $appointDate, 4, 2 );
        }

        //如果查询的是当月, 则连上个月查
        if( ! empty( $appointDate ) && $appointDate != date('Y-m') )
        {
            $startDate = $appointDate . '-01';
            $endDate = date('Y-m-d', strtotime( '+1 month', strtotime( $startDate . ' 00:00:00' ) ) - 1 );;
        }
        else
        {
            $startDate = date('Y-m-01', strtotime( '-1 month') );
            $endDate = date("Y-m-d");
        }

        $data = $this ->getConditionTable_Result( $startDate, $endDate, '
                                                                        f_parcel_id as fParcelId,
                                                                        f_company_name as fCompanyName,
                                                                        f_mail_no as fMailNo,
                                                                        f_recipient_name as fRecipientName,
                                                                        f_recipient_mobile as fRecipientMobile,
                                                                        f_frame_code as fFrameCode,
                                                                        f_num as fNum,
                                                                        f_arrive_time as fArriveTime,
                                                                        f_last_time as fLastTime,
                                                                        f_parcel_status as fParcelStatus,
                                                                        f_take_code as fTakeCode,
                                                                        f_comment as fComment
                                                                        ', "`f_parcel_id`={$parcelId}" )

            ->field('
                        `temp_parcel_info`.*,
                        `temp_parcel_notice_result`.*
                    ')

            //获取站点名, 连表字段需 f_user_id
//            ->join('LEFT JOIN `tp_user` ON `temp_parcel_info`.`fStationId` = `tp_user`.`f_user_id`')
            ->join('LEFT JOIN '. ( new \Home\Server\ParcelNoticeResultServer() )
                                                                    ->getConditionTable_Result(
                                                                            $startDate,
                                                                            $endDate,
                                                                            '
                                                                            `f_parcel_id`,
                                                                            f_weixin_notice AS fWeixinNotice,
                                                                            f_weixin_send_time AS fWeixinSendTime,
                                                                            f_weixin_success_time AS fWeixinSuccessTime,
                                                                            f_sms_notice AS fSmsNotice,
                                                                            f_sms_send_time AS fSmsSendTime,
                                                                            f_sms_success_time AS fSmsSuccessTime,
                                                                            f_address AS fAddress,
                                                                            f_qtime AS fQtime,
                                                                            f_tel AS fTel,
                                                                            f_sms_content AS fSmsContent,
                                                                            f_sms_error AS fSmsError,
                                                                            f_station_name AS fStationName
                                                                            ',
                                                                            "`f_parcel_id`={$parcelId}"
                                                                    ) ->buildSql() .' AS `temp_parcel_notice_result` ON `temp_parcel_info`.`fParcelId` = `temp_parcel_notice_result`.`f_parcel_id`')
//            ->order( $this ->getConditionStatus_Order( $parcel_status ) )
            ->limit("1")
//            ->buildSql()
            ->find()
        ;

        return $data;

    }


    /**
     * @desc 获取包裹详情（筛选字段）
     * @author
     * @update 2017-07-18
     */
    public function queryParcelDetailsForPacket($parcelId, $appointDate = '' )
    {
        //201702  >  2017-02
        if( $appointDate != '' )
        {
            $appointDate = substr( $appointDate, 0, 4 ) . '-' . substr( $appointDate, 4, 2 );
        }

        //如果查询的是当月, 则连上个月查
        if( ! empty( $appointDate ) && $appointDate != date('Y-m') )
        {
            $startDate = $appointDate . '-01';
            $endDate = date('Y-m-d', strtotime( '+1 month', strtotime( $startDate . ' 00:00:00' ) ) - 1 );;
        }
        else
        {
            $startDate = date('Y-m-01', strtotime( '-1 month') );
            $endDate = date("Y-m-d");
        }

        $data = $this ->getConditionTable_Result( $startDate, $endDate, '
                                                                        f_parcel_id as fParcelId,
                                                                        f_company_name as fCompanyName,
                                                                        f_mail_no as fMailNo,
                                                                        f_recipient_name as fRecipientName,
                                                                        f_recipient_mobile as fRecipientMobile,
                                                                        f_frame_code as fFrameCode,
                                                                        f_num as fNum,
                                                                        f_station_id as fStationId,
                                                                        f_arrive_time as fArriveTime,
                                                                        f_last_time as fLastTime,
                                                                        f_out_time as fOutTime,
                                                                        f_parcel_status as fParcelStatus,
                                                                        f_take_code as fTakeCode,
                                                                        f_comment as fComment
                                                                        ', "`f_parcel_id`={$parcelId}" )

            ->field('
                        `temp_parcel_info`.*,
                        `temp_parcel_notice_result`.*
                    ')

            //获取站点名, 连表字段需 f_user_id
//            ->join('LEFT JOIN `tp_user` ON `temp_parcel_info`.`fStationId` = `tp_user`.`f_user_id`')
            ->join('LEFT JOIN '. ( new \Home\Server\ParcelNoticeResultServer() )
                    ->getConditionTable_Result(
                        $startDate,
                        $endDate,
                        '
                                                                            `f_parcel_id`,
                                                                            f_weixin_notice AS fWeixinNotice,
                                                                            f_weixin_send_time AS fWeixinSendTime,
                                                                            f_weixin_success_time AS fWeixinSuccessTime,
                                                                            f_sms_notice AS fSmsNotice,
                                                                            f_sms_send_time AS fSmsSendTime,
                                                                            f_sms_success_time AS fSmsSuccessTime,
                                                                            f_address AS fAddress,
                                                                            f_qtime AS fQtime,
                                                                            f_tel AS fTel,
                                                                            f_sms_content AS fSmsContent,
                                                                            f_sms_error AS fSmsError,
                                                                            f_station_name AS fStationName
                                                                            ',
                        "`f_parcel_id`={$parcelId}"
                    ) ->buildSql() .' AS `temp_parcel_notice_result` ON `temp_parcel_info`.`fParcelId` = `temp_parcel_notice_result`.`f_parcel_id`')
//            ->order( $this ->getConditionStatus_Order( $parcel_status ) )
            ->limit("1")
//            ->buildSql()
            ->find()
        ;

        return $data;

    }
    /**
     * Function updateParcel
     * @param $parcelId
     *
     * Author: quyang
     * Date: 2017-1-20 9:31
     * Info: 更新包裹状态,重新生成提货码
     */
    public function updateParcelTackcode( $stationId, $where, $Array , $new_take_code = '' ){

        //判断是否需要更新提货码
        if ( $new_take_code == '' ){
            //更新提货码
            $Array['f_take_code'] = $this->Allow_TakeCode($stationId,'1')[0];
        }else{
            $Array['f_take_code'] = $new_take_code;
        }

        //更新最近两个月表
        $NowTableResult  = ( new \Think\Model() ) ->table( $this ->Month_TableName_Now ) ->where($where) ->save( $Array );

        $LastTableResult = ( new \Think\Model() ) ->table( $this ->LastTableName ) ->where($where) ->save( $Array );

        if($NowTableResult == true || $LastTableResult == true){
            return $Array['f_take_code'];
        }else{
            return false;
        }

    }

    /**
     * @desc 获取包裹详情（队列扫描）
     * @author quyang
     * @update 2017-1-19
     */
    public function queueParcelDetails(){

        $curday = time();

        $times = $curday-43200;

        $where = "`f_parcel_status`=2 and `f_last_timestamp` between {$times} and {$curday}";

        $field = '
                 *
                 ';

        $data = $this->getUnion_TableResource($field,$where)
            ->field( ' temp_parcel_info.*,
                        ua.f_address,
                        ua.f_store_time,
                        ua.f_user_mobile,
                        ua.f_user_phone,
                        ua.f_station_name'
            )
            ->join('tp_user ua on ua.f_user_id = temp_parcel_info.f_station_id','LEFT')-> select();

        return $data;

    }


    /**
     * @desc 快递公司包裹数量统计
     * @author quyang
     * @update 2017-1-20
     */
    public function countCompanyPacket($data){

        //API版 date数据有用。 如未传 $startDate $endDate。 则数据转换
        if( isset( $data['startDate'] ) && isset( $data['endDate'] ) && $data['startDate'] != 0 && $data['endDate'] != 0 )
        {
            $startDate = $data['startDate'];
            $endDate = $data['endDate'];
        }
        elseif ( $data['date'] > 0 )
        {
            //开始日期
            $startDate = substr( $data['date'], 0, 4 ) . '-' . substr( $data['date'], 4, 2 ) . '-01';

            //结束日期
            $endDate = date('Y-m-d', strtotime( '+1 month', strtotime( $startDate . ' 00:00:00' ) ) - 1 );
        }
        else
        {
            $startDate = date('Y-m-01',strtotime('-1 month'));
            $endDate = date('Y-m-d');
        }

        //查询条件SQL
        $ConditionSQL = $this->getConditionSQL($data['stationId'], '', '', $data['state']);

        //数据查询
         return $this ->getConditionTable_Result( $startDate, $endDate, 'f_parcel_id,f_company_id as companyId,f_company_name as companyName', $ConditionSQL )
             ->field('*,count(f_parcel_id) as count')
                    ->group('companyId')
                    ->select();

    }

    /**
     * @desc 查询包裹是否存在
     * @author quyang
     * @update 2017-1-20
     */
    public function queryParcelStatus($data){

        $where = $data;

        $field = '*';

        $data = $this->getUnion_TableResource($field,$where)->find();

        return $data;

    }

    /**
     * @desc 根据站点ID查询包裹状态为通知失败的包裹数量
     * @author youtanzhi
     * @update 2017-1-20
     */
    public function queryParcel($data){
        $count  = ( new \Think\Model() ) ->table( $this ->Month_TableName_Now ) ->where($data) ->count(true);
        return $count;
    }

    /**
     * Function replaceSms
     * @param $parcelId
     * @return mixed
     *
     * Author: 黄盖
     * Date: 2017-2-9 17:06
     * Info:     获取短信替换信息
                    改于 quyang
                         2017-1-14
     */
    public function replaceSms( $parcelId )
    {
        $data = D('tp_user')->alias('u')
            ->where(array('u.f_user_id'=>$parcelId))
            ->field('
                     u.f_address as address,
                     u.f_store_time as openTime,
                     u.f_company_name as companyName,
                     u.f_store_time as openTime
                     ')->find();
        return $data;
    }

    /**
     * @desc 代理获取包裹详情（统计）
     * @author quyang
     * @update 2017-1-19
     */
    public function countProxyQueryParcel($where){

        $data = $this->getUnion_TableResource('`f_parcel_id`',$where)->count('`f_parcel_id`');

        return $data;

    }

    /**
     * @desc 代理获取包裹详情
     * @author quyang
     * @update 2017-1-19
     */
    public function proxyQueryParcel($where,$page,$pageNum){

        $field = '
                f_parcel_id as fParcelId,
                f_parcel_status as fParcelStatus,
                f_num as fNum,
                f_mail_no as fMailNo,
                f_arrive_time as fArriveTime,
                f_out_time as fOutTime,
                f_recipient_name as fRecipientName,
                f_recipient_mobile as fRecipientmobile,
                f_last_time as fLastTime,
                f_branch_id as fBranchId,
                f_company_id as fCompanyId,
                f_company_name as fCompanyName,
                f_frame_code as fFrameCode,
                f_input_source as fInputSource,
                f_input_way as fInputWay,
                f_is_detention as fIsDetention,
                f_out_source as fOutSource,
                f_out_way as fOutWay,
                f_station_id as fStationId,
                f_take_code as fTakeCode,
                f_type as fType,
                f_comment as fComment,
                f_arrive_timestamp AS fArriveTimestamp,
                FROM_UNIXTIME( `f_arrive_timestamp`, \'%Y-%m-%d %H:%i:%S\') AS fArriveTimeDate,
                
                `f_last_timestamp` AS fLastTimestamp,
                FROM_UNIXTIME( `f_last_timestamp`, \'%Y-%m-%d %H:%i:%S\') AS fLastTimeDate,
                
                `f_out_timestamp` AS `fOutTimestamp`,
                FROM_UNIXTIME( `f_out_timestamp`, \'%Y-%m-%d %H:%i:%S\') AS `fOutTimesDate`
                 ';

        $data = $this->getUnion_TableResource($field,$where)
            ->field( ' temp_parcel_info.*,
                        r.f_weixin_notice as fWeixinNotice,
                        r.f_weixin_send_time as fWeixinSendTime,
                        r.f_weixin_success_time as fWeixinSuccessTime,
                        r.f_sms_notice as fSmsNotice,
                        r.f_sms_send_time as fSmsSendTime,
                        r.f_sms_success_time as fSmsSuccessTime,
                        r.f_address as fAddress,
                        r.f_qtime as fQtime,
                        r.f_tel as fTel,
                        r.f_sms_content as fSmsContent,
                        r.f_sms_error as fSmsError,
                        r.f_station_name as fStationName
                     ')
//            ->join('tp_parcel_notice_result r on temp_parcel_info.fParcelId = r.f_parcel_id','LEFT')
            ->join('LEFT JOIN '. ( new \Home\Server\ParcelNoticeResultServer() ) ->getConditionTable_Result( date( 'Y-m-01' , strtotime(  '-1 month' ) ) , date('Y-m-d'), '*', $where ) ->buildSql() .' AS `r` ON `temp_parcel_info`.`fParcelId` = `r`.`f_parcel_id`')
            ->page($page,$pageNum)-> select();

        return $data;

    }

    /**
     * Function getOneParcel_Data
     * @param $parcelID
     * @param string $tableName
     *
     * Author: 黄盖
     * Date: 2017-4-7 10:53
     * Info: 根据包裹ID, 查询单条包裹信息
     */
    public function getOneParcel_Data( $parcelID )
    {
        return $this ->getUnion_TableResource('`f_parcel_id`, `f_num`', "`f_parcel_id` = {$parcelID}") ->find();
    }

    /**
     * @Desc  : 拒收出库
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/2 16:53
     * @Update：2017/5/2
     **/
    public function outRejectParcel( $stationId , $parcelId , $content = '' , $status , $tableName = '' )
    {

        //拒收件才可以拒收出库
        $where = "`f_station_id` = {$stationId} AND `f_parcel_id` in (".$parcelId.") AND `f_parcel_status` = 4";

        $update_data = [
            'f_parcel_status'   => $status,
            'f_out_time'        => date( 'YmdHis' ),
            'f_out_timestamp'   => time(),
            'f_last_time'       => date( 'YmdHis' ),
            'f_last_timestamp'  => time()
        ];

        if ( $content != '' )
        {
            $update_data['f_comment'] = $content;
        }


        if ( $tableName != '' )
        {
            return ( new \Think\Model( $tableName ) )->where( $where )->save( $update_data );
        }

        //更新最近两个月表
        $NowTableResult  = ( new \Think\Model() ) ->table( $this ->Month_TableName_Now ) ->where($where) ->save( $update_data );

        $LastTableResult = ( new \Think\Model() ) ->table( $this ->LastTableName ) ->where($where) ->save( $update_data );

        return $NowTableResult || $LastTableResult ? True : False;

    }

}